//
//  LCRmbHtmlVC.m
//  LC
//
//  Generated at 1:59 下午, GMT+8星期六, 一月 27, 2018
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCRmbHtmlVC.h"
#import "WKWebView+PAWebCache.h"

@interface LCRmbHtmlVC () 

@end

@implementation LCRmbHtmlVC

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.progressView.hidden = YES;
}
- (void)dealloc {
    [self.webView clearHTMLCache];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
- (void)loadView {
    [super loadView];
    NSString *usercode = [[NSUserDefaults standardUserDefaults] objectForKey:@"usercode"];
    _link = [NSString stringWithFormat:@"http://fuyin.app.inping.com/user/donation_rmb?usercode=%@",usercode];
    NSLog(@"调转链接 %@",_link);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"奉献支持";

    [self setupWebView];
    [self setupProgressView];
}
- (void)setupProgressView {
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.progressView];
    [self.progressView bringSubviewToFront:self.view];
    self.progressView.progressTintColor = [UIColor colorWithRed:232/255.0 green:45/255.0 blue:51/255.0 alpha:1];
    self.progressView.trackTintColor = [UIColor clearColor];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.webView).offset(0);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(2);
    }];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)setupWebView {
    // 根据生成的WKUserScript对象，初始化WKWebViewConfiguration
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config];
    self.webView.allowsBackForwardNavigationGestures = YES;//是否允许左右划手势导航,默认不允许
    
    [self.view addSubview:self.webView];
    self.webView.scrollView.bounces = NO;//禁止WebView滚动和回弹方法
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.link]];//创建URL
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:5];//创建NSURLRequest
    [self.webView loadRequest:request];//加载
    [self setupWebViewLayout];
}
- (void)setupWebViewLayout
{
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        if (@available(iOS 11, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-0);
        }else{
            make.top.equalTo(self.view.mas_top);
            make.bottom.equalTo(self.view.mas_bottom).offset(-0);
        }
    }];
}

- (void)setupWebViewCompatibilityADLayout
{
    CGFloat width = MIN(self.view.width , self.view.height);
    [_webView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        if (@available(iOS 11, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-width/20*3);
        }else{
            make.top.equalTo(self.view.mas_top);
            make.bottom.equalTo(self.view.mas_bottom).offset(-width/20*3);
        }
    }];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        
        if (self.webView.estimatedProgress < 1.0) {
            self.delayTime = 1 - self.webView.estimatedProgress;
            return;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.progress = 0;
        });
        
    }
}

/**
 *  在发送请求之前，决定是否跳转
 *
 *  @param webView          实现该代理的webview
 *  @param navigationAction 当前navigation
 *  @param decisionHandler  是否调转block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSString *url = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    NSLog(@"url = %@", url);
    
    if ([url containsString:@"alipay://"]) {//支付宝
        // url = alipay://alipayclient/?{"dataString":"h5_route_token=\"b623dcdee2328a907b74556a684cc4a7\"&is_h5_route=\"true\"","requestType":"SafePay","fromAppUrlScheme":"alipays"}
        NSString* dataStr=[url substringFromIndex:23];
        NSLog(@"%@",dataStr);
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[dataStr dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
        NSMutableString* mString=[[NSMutableString alloc] init];
        [mString appendString:@"alipays://platformapi/startApp?appId=20000125&orderSuffix="];
        //url进行编码
        [mString appendString:[self encodeString:dict[@"dataString"]]];
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mString]];
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }else if ([url containsString:@"weixin://"]) {
        
        NSDictionary *requestHeaders = navigationAction.request.allHTTPHeaderFields;
        if (requestHeaders[@"Referer"]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
            decisionHandler(WKNavigationActionPolicyCancel);//不允许跳转
            return;
        }else{
            NSMutableURLRequest *mutableRequest = [navigationAction.request mutableCopy];
            [mutableRequest setValue:@"http://buy.9ku.com/" forHTTPHeaderField:@"Referer"];
            [webView loadRequest:mutableRequest];
        }
        
        decisionHandler(WKNavigationActionPolicyCancel);//这个地方必须进行不跳转
        return;
    }
    // 允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
}
- (NSString*)encodeString:(NSString*)unencodedString {
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return encodedString;
}

//加载完成时调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
//    NSMutableString *JSString = [NSMutableString string];
//    [JSString appendString:@"var bottomTag = document.getElementsByClassName('header')[0];bottomTag.parentNode.removeChild(bottomTag);"];
//    [webView evaluateJavaScript:JSString completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//        NSLog(@"result = %@", result);
//    }];

}
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

// 提示框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示框" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

@end
